package com.smart.community.user.service.impl;

import com.smart.community.commons.utils.SecurityUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.result.PageResult;
import com.smart.community.user.dto.PermissionDTO;
import com.smart.community.user.dto.PermissionQueryDTO;
import com.smart.community.user.entity.Permission;
import com.smart.community.user.entity.RolePermission;
import com.smart.community.user.mapper.PermissionMapper;
import com.smart.community.user.mapper.RolePermissionMapper;
import com.smart.community.user.service.PermissionService;
import com.smart.community.user.vo.PermissionVO;

import cn.hutool.core.util.StrUtil;
import io.seata.spring.annotation.GlobalTransactional;

/**
 * 权限服务实现
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private static final Logger log = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    @Cacheable(value = "permission:list", key = "#queryDTO.current + ':' + #queryDTO.size + ':' + #queryDTO.permissionName + ':' + #queryDTO.permissionCode + ':' + #queryDTO.status", unless = "#result == null || #result.getRecords().isEmpty()")
    public PageResult<PermissionVO> getPermissionList(PermissionQueryDTO queryDTO) {
        // 构建查询条件
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getPermissionName())) {
            queryWrapper.like("permission_name", queryDTO.getPermissionName());
        }
        
        if (StringUtils.hasText(queryDTO.getPermissionCode())) {
            queryWrapper.like("permission_code", queryDTO.getPermissionCode());
        }
        
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }
        
        queryWrapper.orderByAsc("sort_order", "create_time");
        
        // 分页查询
        Page<Permission> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        IPage<Permission> permissionPage = this.page(page, queryWrapper);
        
        // 转换为VO
        List<PermissionVO> permissionVOList = permissionPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return new PageResult<>(queryDTO.getCurrent(), queryDTO.getSize(), permissionPage.getTotal(), permissionVOList);
    }

    @Override
    @Cacheable(value = "permission:detail", key = "#id", unless = "#result == null")
    public PermissionVO getPermission(Long id) {
        Permission permission = this.getById(id);
        return permission != null ? convertToVO(permission) : null;
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"permission:list", "permission:detail", "permission:tree", "permission:user", "permission:role"}, allEntries = true)
    public void createPermission(PermissionDTO permissionDTO) throws Exception {
        // 检查权限编码是否已存在
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_code", permissionDTO.getPermissionCode());
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("权限编码已存在");
        }
        
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionDTO, permission);
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        
        this.save(permission);
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"permission:list", "permission:detail", "permission:tree", "permission:user", "permission:role"}, allEntries = true)
    public void updatePermission(Long id, PermissionDTO permissionDTO) throws Exception {
        Permission permission = this.getById(id);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        // 检查权限编码是否重复（排除自己）
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_code", permissionDTO.getPermissionCode())
                .ne("id", id);
        if (this.count(queryWrapper) > 0) {
            throw new RuntimeException("权限编码已存在");
        }
        
        BeanUtils.copyProperties(permissionDTO, permission);
        permission.setUpdateTime(LocalDateTime.now());
        
        this.updateById(permission);
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"permission:list", "permission:detail", "permission:tree", "permission:user", "permission:role"}, allEntries = true)
    public void deletePermission(Long id) throws Exception {
        // 检查是否有角色关联此权限
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_id", id);
        if (rolePermissionMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("该权限已被角色使用，无法删除");
        }
        
        this.removeById(id);
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"permission:list", "permission:detail", "permission:tree", "permission:user", "permission:role"}, allEntries = true)
    public void updatePermissionStatus(Long id, Integer status) throws Exception {
        Permission permission = this.getById(id);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        permission.setStatus(status);
        permission.setUpdateTime(LocalDateTime.now());
        
        this.updateById(permission);
    }

    @Override
    @Cacheable(value = "permission:tree", key = "#status", unless = "#result == null || #result.isEmpty()")
    public List<PermissionVO> getPermissionTree(Integer status) throws Exception {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByAsc("sort_order", "create_time");
        
        List<Permission> permissions = this.list(queryWrapper);
        
        return permissions.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<PermissionVO> getCompletePermissionTree(Integer status) throws Exception {
        // 调用Mapper的selectCompletePermissionTree方法
        List<Permission> permissions = baseMapper.selectCompletePermissionTree(status)
        		.stream().filter(p -> !StrUtil.isBlankIfStr(p.getPermissionCode()) && !p.getPermissionCode().startsWith("mobile:")).collect(Collectors.toList());
        
        // 转换为VO并构建树形结构
        List<PermissionVO> permissionVOList = permissions.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建树形结构
        return buildPermissionTree(permissionVOList);
    }

    @Override
    @Cacheable(value = "permission:user", key = "#userId", unless = "#result == null || #result.isEmpty()")
    public List<PermissionVO> getUserPermissions(Long userId) {
        List<Permission> permissions = baseMapper.getPermissionsByUserId(userId);
        return permissions.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(value = "permission:role", key = "#roleId", unless = "#result == null || #result.isEmpty()")
    public List<PermissionVO> getRolePermissions(Long roleId) {
        List<Permission> permissions = baseMapper.getPermissionsByRoleId(roleId);
        return permissions.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }



    @Override
    public List<Permission> getPermissionsByUserId(Long userId) throws Exception {
        return baseMapper.getPermissionsByUserId(userId);
    }

    @Override
    public boolean hasPermission(Long userId, String permissionCode) throws Exception {
        List<Permission> permissions = baseMapper.getPermissionsByUserId(userId);
        return permissions.stream()
                .anyMatch(permission -> permissionCode.equals(permission.getPermissionCode()));
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) throws Exception {
        return baseMapper.getPermissionsByRoleId(roleId);
    }

    @Override
    public List<String> getCurrentUserMenuPermissions() throws Exception {
        // 根据架构设计：网关负责Token验证，下游服务无需重复验证Token
        // 直接从用户上下文获取用户信息
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            log.warn("用户上下文为空，无法获取当前用户ID");
            throw new RuntimeException("用户信息获取失败，无法获取菜单权限");
        }
        
        log.debug("从用户上下文获取用户ID: {}", userId);
        
        // 开始查询用户权限 - 已隐藏详细日志
        
        // 查询该用户的所有权限，筛选菜单权限
        List<Permission> permissions = getPermissionsByUserId(userId);
        List<String> menuPermissions = new java.util.ArrayList<>();
        
        if (permissions != null) {
            // 用户权限数量 - 已隐藏详细日志
            for (Permission p : permissions) {
                if (p != null && p.getPermissionCode() != null && ("MENU".equals(p.getType()) || p.getType() == null)) {
                    menuPermissions.add(p.getPermissionCode());
                }
            }
        } else {
            log.warn("用户权限列表为空，用户ID: {}", userId);
        }
        
        // 去重，防止前端递归死循环
        List<String> distinctPermissions = menuPermissions.stream().distinct().collect(java.util.stream.Collectors.toList());
        log.info("用户菜单权限获取成功，用户ID: {}, 权限数量: {}", userId, distinctPermissions.size());
        
        return distinctPermissions;
    }

    /**
     * 转换为VO
     */
    private PermissionVO convertToVO(Permission permission) {
        PermissionVO vo = new PermissionVO();
        BeanUtils.copyProperties(permission, vo);
        // 手动映射字段，确保前后端一致
        vo.setSortOrder(permission.getSortOrder());
        // 移除对不存在的remark字段的引用
        // vo.setDescription(permission.getRemark());
        return vo;
    }
    
    /**
     * 构建权限树形结构
     *
     * @param permissionVOList 权限列表
     * @return 树形结构的权限列表
     */
    private List<PermissionVO> buildPermissionTree(List<PermissionVO> permissionVOList) {
        // 创建根节点列表
        List<PermissionVO> rootNodes = new ArrayList<>();
        
        // 创建ID到权限的映射
        Map<Long, PermissionVO> permissionMap = new HashMap<>();
        for (PermissionVO permission : permissionVOList) {
            permissionMap.put(permission.getId(), permission);
        }
        
        // 构建树形结构
        for (PermissionVO permission : permissionVOList) {
            if (permission.getParentId() == null || permission.getParentId() == 0) {
                // 根节点
                rootNodes.add(permission);
            } else {
                // 子节点
                PermissionVO parent = permissionMap.get(permission.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(permission);
                }
            }
        }
        
        return rootNodes;
    }
} 